package com.games.portal.main;


import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.database.Cursor;
import android.os.Build;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.LoaderManager.LoaderCallbacks;
import android.support.v4.content.CursorLoader;
import android.support.v4.content.Loader;
import android.support.v4.widget.CursorAdapter;
import android.support.v4.widget.SimpleCursorAdapter;
import android.util.Log;
import android.view.MenuItem;
import android.view.View;
import android.view.Window;
import android.widget.Adapter;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.ImageButton;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.games.portal.db.GamesDatabase;
import com.games.portal.db.GamesProvider;
import com.games.portal.model.Game;
import com.games.portal.model.builder.ListItemBuilder;
import com.games.portal.service.Html5ServiceHelper;
import com.games.widget.MenuDrawer;
import com.games.widget.MenuDrawerManager;

public class WindowSample extends FragmentActivity implements LoaderCallbacks<Cursor>   {

	private static final String STATE_MENUDRAWER = "net.simonvt.menudrawer.samples.WindowSample.menuDrawer";
	private static final String STATE_ACTIVE_VIEW_ID = "net.simonvt.menudrawer.samples.WindowSample.activeViewId";

	private MenuDrawerManager mMenuDrawer;
	private int mActiveViewId;
	private BroadcastReceiver brdcstRcvr;
	private Html5ServiceHelper serivceHelper;
	private boolean isBroadCastEventRegistered;
	private static final int LOADER_ID = 0x02;
	private CursorAdapter adapterGameCategory;
	private  ArrayAdapter<String> adapterGameName;
	private  ListView listViewGameName;
	protected HashMap<String, List<Game>> map;
	private ArrayList<String> listGameName = new ArrayList<String>();
	private ListView listViewCatName;
	@Override
	public void onCreate(Bundle inState) {

		super.onCreate(inState);
		final boolean customTitleSupported = requestWindowFeature(Window.FEATURE_CUSTOM_TITLE);

		if (inState != null) {
			mActiveViewId = inState.getInt(STATE_ACTIVE_VIEW_ID);
		}

		Log.d("onCreate", "onCreate called");
		setBroadcastReciever();
		isBroadCastEventRegistered = true;

		mMenuDrawer = new MenuDrawerManager(this, MenuDrawer.MENU_DRAG_WINDOW);
		mMenuDrawer.setContentView(R.layout.activity_windowsample);
		mMenuDrawer.setMenuView(R.layout.menu_scrollview);

		if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH) {
			getActionBar().setDisplayHomeAsUpEnabled(true);
		}
		


		listViewGameName = (ListView)findViewById(R.id.mylistActive);





		adapterGameCategory = new SimpleCursorAdapter(this, R.layout.menu_row_item, null,
				new String[]{GamesDatabase.COL_CATEGORY_NAME}, new int[]{R.id.myrow},
				Adapter.NO_SELECTION);

		adapterGameName = new ArrayAdapter<String>(this,
				R.layout.menu_row_item_active,R.id.myrow_active, listGameName);
		listViewGameName.setAdapter(adapterGameName);

	    listViewCatName = (ListView) findViewById(R.id.mylist);
		listViewCatName.setAdapter(adapterGameCategory);
		listViewCatName.setOnItemClickListener(new OnItemClickListener () {

			@Override
			public void onItemClick(AdapterView<?> adapterView, View view, int poisition,
					long arg3) {
				mMenuDrawer.setActiveView(view);
				if (map != null && !map.isEmpty()) {
				    Cursor c = (Cursor) adapterView.getItemAtPosition(poisition);
				    String textItem = c.getString(1);
					List<Game> gameList = map.get(textItem);
					listGameName.clear();
					for (Game game : gameList) {
						listGameName.add(game.getName());
					}
					adapterGameName.notifyDataSetChanged();
				}
				mMenuDrawer.closeMenu();
				mActiveViewId = view.getId();
			}
		});



		if ( customTitleSupported ) {
			getWindow().setFeatureInt(Window.FEATURE_CUSTOM_TITLE, R.layout.titlebar);
		}


		final ImageButton button = (ImageButton) findViewById(R.id.pushButton);
		button.setOnClickListener(new View.OnClickListener() {
			public void onClick(View v) {
				mMenuDrawer.toggleMenu();
			}
		});
		
		getSupportLoaderManager().initLoader(LOADER_ID, null, this);

	}

	@Override
	protected void onRestoreInstanceState(Bundle inState) {
		super.onRestoreInstanceState(inState);
		mMenuDrawer.onRestoreDrawerState(inState.getParcelable(STATE_MENUDRAWER));
	}

	@Override
	protected void onSaveInstanceState(Bundle outState) {
		super.onSaveInstanceState(outState);
		outState.putParcelable(STATE_MENUDRAWER, mMenuDrawer.onSaveDrawerState());
		outState.putInt(STATE_ACTIVE_VIEW_ID, mActiveViewId);
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case android.R.id.home:
			mMenuDrawer.toggleMenu();
			return true;
		}

		return super.onOptionsItemSelected(item);
	}

	@Override
	public void onBackPressed() {
		final int drawerState = mMenuDrawer.getDrawerState();
		if (drawerState == MenuDrawer.STATE_OPEN || drawerState == MenuDrawer.STATE_OPENING) {
			mMenuDrawer.closeMenu();
			return;
		}

		super.onBackPressed();
	}

	/**
	 * register broadcast event to rest GET operation
	 */
	 private void setBroadcastReciever() {
		IntentFilter intentFilter = new IntentFilter(Html5ServiceHelper.ACTION_REQUEST_RESULT);
		brdcstRcvr = new BroadcastReceiver() {

			@Override
			public void onReceive(Context context, Intent intent) {
				int resultCode = intent.getIntExtra(Html5ServiceHelper.EXTRA_RESULT_CODE, 0);
				if (resultCode == 200) {
					context.getContentResolver().notifyChange(GamesProvider.CONTENT_URI, null);
				}
			}
		};

		serivceHelper = Html5ServiceHelper.getInstance(this);
		//register
		this.registerReceiver(brdcstRcvr, intentFilter);
		//get list of games
		serivceHelper.getGamesList();
		
		
		
	 }


	 @Override
	 protected void onStop() {
		 Log.d("onCreate", "onStop called");
		 super.onStop();
		 if (brdcstRcvr != null && isBroadCastEventRegistered) {
			 this.unregisterReceiver(brdcstRcvr);
			 isBroadCastEventRegistered = false;
		 }
	 }

	 public Loader<Cursor> onCreateLoader(int i, Bundle bundle) {

		 return new CursorLoader(this,
				 (GamesProvider.CONTENT_URI)
				 , new String[]{GamesDatabase.ID,GamesDatabase.COL_CATEGORY_NAME,GamesDatabase.COL_NAME,GamesDatabase.COL_URL,GamesDatabase.COL_IMAGE_URL}, null, null, null);
	 }

	 public void onLoadFinished(Loader<Cursor> cursorLoader, Cursor cursor) {
		 if (cursor != null && cursor.getCount() > 0) {
			 cursor.moveToFirst();
				 map = new HashMap<String,List<Game>>(); 

			 while (cursor.isAfterLast() == false) {
				 Game game = ListItemBuilder.create().addCategoryName( cursor.getString(cursor.getColumnIndex(GamesDatabase.COL_CATEGORY_NAME)))
						 .addImageUrl(cursor.getString(cursor.getColumnIndex(GamesDatabase.COL_IMAGE_URL)))
						 .addName(cursor.getString(cursor.getColumnIndex(GamesDatabase.COL_NAME)))
						 .addUrl(cursor.getString(cursor.getColumnIndex(GamesDatabase.COL_URL)))
						 .build();
				 List<Game> list = map.get(game.getCategoryName());
				 if (list == null) {
					 list = new ArrayList<Game>();
				 }

				 list.add(game);

				 map.put(game.getCategoryName(), list);
				 cursor.moveToNext();

			 }
		 }
		 adapterGameCategory.swapCursor(cursor);
	 }

	 public void onLoaderReset(Loader<Cursor> cursorLoader) {
		 adapterGameCategory.swapCursor(null);
	 }

}
